import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Eye, EyeOff, Save, Key, AlertCircle, CheckCircle2, RefreshCw, Palette, FileText, Settings as SettingsIcon, User, Shield, Bell, Trash2 } from 'lucide-react';
import { getProviders, saveProviders, refreshProviderModels, type AIProvider } from '@/lib/ai-config';
import { aiPromptsAPI, type AIPromptConfig } from '@/lib/apiClient';
import ThemeToggle from '@/components/ThemeToggle';
import ColorThemeSelector from '@/components/ColorThemeSelector';
import { useTheme } from '@/lib/theme';

export default function Settings() {
  const { theme, actualTheme } = useTheme();
  const [activeTab, setActiveTab] = useState('theme');
  
  // AI提供商配置状态
  const [providers, setProviders] = useState<AIProvider[]>([]);
  const [showKeys, setShowKeys] = useState<{ [key: string]: boolean }>({});
  const [saved, setSaved] = useState(false);
  const [refreshing, setRefreshing] = useState<{ [key: string]: boolean }>({});
  
  // 提示词配置状态
  const [emailPrompt, setEmailPrompt] = useState('');
  const [emailPromptId, setEmailPromptId] = useState<number | null>(null);
  const [promptSaved, setPromptSaved] = useState(false);
  const [promptLoading, setPromptLoading] = useState(false);
  const [promptError, setPromptError] = useState('');

  useEffect(() => {
    const loadedProviders = getProviders();
    setProviders(loadedProviders);
  }, []);

  useEffect(() => {
    if (activeTab === 'prompts') {
      loadEmailPrompt();
    }
  }, [activeTab]);

  const loadEmailPrompt = async () => {
    try {
      setPromptLoading(true);
      setPromptError('');
      const response = await aiPromptsAPI.getByModule('email');
      setEmailPrompt(response.prompt.prompt_template);
      setEmailPromptId(response.prompt.id);
    } catch (error) {
      console.error('加载提示词失败:', error);
      setPromptError('加载提示词失败，请稍后重试');
    } finally {
      setPromptLoading(false);
    }
  };

  const handleApiKeyChange = (providerId: string, newApiKey: string) => {
    setProviders(prev =>
      prev.map(p => (p.id === providerId ? { ...p, apiKey: newApiKey } : p))
    );
  };

  const handleEnabledToggle = (providerId: string) => {
    setProviders(prev =>
      prev.map(p => (p.id === providerId ? { ...p, enabled: !p.enabled } : p))
    );
  };

  const handleSaveProviders = () => {
    try {
      saveProviders(providers);
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (error) {
      console.error(error);
      alert('保存失败，请重试');
    }
  };

  const toggleShowKey = (providerId: string) => {
    setShowKeys(prev => ({ ...prev, [providerId]: !prev[providerId] }));
  };

  const handleRefreshModels = async (providerId: string) => {
    setRefreshing(prev => ({ ...prev, [providerId]: true }));
    try {
      await refreshProviderModels(providerId);
      // 重新加载提供商列表
      const updatedProviders = getProviders();
      setProviders(updatedProviders);
      alert('模型列表更新成功！');
    } catch (error) {
      alert(error instanceof Error ? error.message : '刷新失败，请检查配置');
    } finally {
      setRefreshing(prev => ({ ...prev, [providerId]: false }));
    }
  };

  const handleSaveEmailPrompt = async () => {
    if (!emailPrompt.trim()) {
      setPromptError('提示词不能为空');
      return;
    }

    try {
      setPromptLoading(true);
      setPromptError('');
      
      if (emailPromptId) {
        await aiPromptsAPI.update(emailPromptId, {
          prompt_template: emailPrompt
        });
      } else {
        const response = await aiPromptsAPI.create({
          module: 'email',
          prompt_template: emailPrompt,
          is_active: true
        });
        setEmailPromptId(response.prompt.id);
      }
      
      setPromptSaved(true);
      setTimeout(() => setPromptSaved(false), 3000);
    } catch (error) {
      console.error('保存提示词失败:', error);
      setPromptError('保存失败，请稍后重试');
    } finally {
      setPromptLoading(false);
    }
  };

  const handleResetEmailPrompt = async () => {
    if (!confirm('确定要恢复默认提示词吗？')) {
      return;
    }

    try {
      setPromptLoading(true);
      setPromptError('');
      const response = await aiPromptsAPI.resetToDefault('email');
      setEmailPrompt(response.prompt.prompt_template);
      setEmailPromptId(response.prompt.id);
      alert('已恢复为默认提示词');
    } catch (error) {
      console.error('重置提示词失败:', error);
      setPromptError('重置失败，请稍后重试');
    } finally {
      setPromptLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Page header */}
      <div>
        <h1 className="text-3xl font-bold">设置</h1>
        <p className="text-muted-foreground">管理您的账户和系统设置</p>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="theme" className="flex items-center gap-2">
            <Palette className="h-4 w-4" />
            主题
          </TabsTrigger>
          <TabsTrigger value="ai" className="flex items-center gap-2">
            <Key className="h-4 w-4" />
            AI配置
          </TabsTrigger>
          <TabsTrigger value="prompts" className="flex items-center gap-2">
            <FileText className="h-4 w-4" />
            提示词管理
          </TabsTrigger>
          <TabsTrigger value="other" className="flex items-center gap-2">
            <SettingsIcon className="h-4 w-4" />
            其他
          </TabsTrigger>
        </TabsList>

        {/* 主题设置 Tab */}
        <TabsContent value="theme" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <Palette className="h-5 w-5" />
                <CardTitle>主题设置</CardTitle>
              </div>
              <CardDescription>
                自定义您的界面外观，选择明亮模式、暗黑模式或主题颜色
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* 主题模式 */}
              <div className="space-y-3">
                <div className="text-sm font-medium">主题模式</div>
                <div className="flex items-center gap-4">
                  <ThemeToggle variant="button" showLabel />
                  <div className="flex-1">
                    <p className="text-sm text-muted-foreground">
                      当前：{theme === 'light' ? '明亮模式' : theme === 'dark' ? '暗黑模式' : '跟随系统'}
                      {theme === 'system' && ` (${actualTheme === 'light' ? '明亮' : '暗黑'})`}
                    </p>
                  </div>
                </div>
              </div>

              <Separator />

              {/* 颜色主题 */}
              <ColorThemeSelector />
            </CardContent>
          </Card>
        </TabsContent>

        {/* AI配置 Tab */}
        <TabsContent value="ai" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <Key className="h-5 w-5" />
                <CardTitle>AI 提供商配置</CardTitle>
              </div>
              <CardDescription>
                配置您的 API Key，数据仅存储在本地浏览器中，不会上传到服务器
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {providers.map((provider) => (
                <div key={provider.id} className="space-y-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <h3 className="text-lg font-semibold">{provider.name}</h3>
                      <Badge variant={provider.enabled ? 'default' : 'secondary'}>
                        {provider.enabled ? '已启用' : '已禁用'}
                      </Badge>
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleEnabledToggle(provider.id)}
                    >
                      {provider.enabled ? '禁用' : '启用'}
                    </Button>
                  </div>

                  <div className="grid gap-2">
                    <label className="text-sm font-medium">API Key</label>
                    <div className="relative">
                      <Input
                        type={showKeys[provider.id] ? 'text' : 'password'}
                        value={provider.apiKey}
                        onChange={(e) => handleApiKeyChange(provider.id, e.target.value)}
                        placeholder={
                          provider.id === 'ollama'
                            ? 'Ollama 不需要配置 API Key'
                            : '请输入您的 API Key'
                        }
                        className="pr-10"
                        disabled={provider.id === 'ollama'}
                      />
                      {provider.id !== 'ollama' && (
                        <button
                          type="button"
                          onClick={() => toggleShowKey(provider.id)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                        >
                          {showKeys[provider.id] ? (
                            <EyeOff className="h-4 w-4" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </button>
                      )}
                    </div>
                  </div>

                  <div className="grid gap-2">
                    <label className="text-sm font-medium">API 地址</label>
                    <Input value={provider.baseUrl} disabled className="bg-muted" />
                  </div>

                  <div className="grid gap-2">
                    <label className="text-sm font-medium">模型列表</label>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleRefreshModels(provider.id)}
                        disabled={refreshing[provider.id] || (!provider.apiKey && provider.id !== 'ollama')}
                        className="gap-2"
                      >
                        <RefreshCw className={`h-4 w-4 ${refreshing[provider.id] ? 'animate-spin' : ''}`} />
                        {refreshing[provider.id] ? '刷新中...' : '刷新模型列表'}
                      </Button>
                      <Badge variant="secondary">{provider.models.length} 个模型</Badge>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {provider.id === 'ollama' 
                        ? '自动检测已安装的 Ollama 模型'
                        : '从提供商 API 获取最新可用模型'}
                    </p>
                  </div>

                  <div className="flex items-start gap-2 rounded-lg bg-muted p-3 text-sm">
                    <AlertCircle className="h-4 w-4 mt-0.5 text-muted-foreground flex-shrink-0" />
                    <div className="space-y-1">
                      <p className="font-medium">如何获取 API Key？</p>
                      <p className="text-muted-foreground text-xs">
                        {provider.id === 'aliyun' && (
                          <>
                            访问{' '}
                            <a
                              href="https://dashscope.console.aliyun.com/apiKey"
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-primary hover:underline"
                            >
                              阿里云百炼控制台
                            </a>{' '}
                            获取 API Key
                          </>
                        )}
                        {provider.id === 'deepseek' && (
                          <>
                            访问{' '}
                            <a
                              href="https://platform.deepseek.com/api_keys"
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-primary hover:underline"
                            >
                              DeepSeek 平台
                            </a>{' '}
                            创建 API Key
                          </>
                        )}
                        {provider.id === 'ollama' && (
                          <>
                            Ollama 是本地运行的模型，需要先{' '}
                            <a
                              href="https://ollama.com/download"
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-primary hover:underline"
                            >
                              下载安装 Ollama
                            </a>
                          </>
                        )}
                      </p>
                    </div>
                  </div>

                  {provider.id !== providers[providers.length - 1].id && (
                    <Separator className="mt-4" />
                  )}
                </div>
              ))}

              <div className="flex items-center justify-between pt-4">
                <div className="flex items-center gap-2">
                  {saved && (
                    <div className="flex items-center gap-2 text-sm text-green-600">
                      <CheckCircle2 className="h-4 w-4" />
                      <span>保存成功</span>
                    </div>
                  )}
                </div>
                <Button onClick={handleSaveProviders} className="gap-2">
                  <Save className="h-4 w-4" />
                  保存配置
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 提示词管理 Tab */}
        <TabsContent value="prompts" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <FileText className="h-5 w-5" />
                <CardTitle>Email AI总结提示词</CardTitle>
              </div>
              <CardDescription>
                自定义邮件AI总结的提示词模板。支持变量：<code className="text-xs bg-muted px-1 py-0.5 rounded">{'{subject}'}</code>, <code className="text-xs bg-muted px-1 py-0.5 rounded">{'{sender}'}</code>, <code className="text-xs bg-muted px-1 py-0.5 rounded">{'{content}'}</code>
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {promptError && (
                <Alert variant="destructive">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>{promptError}</AlertDescription>
                </Alert>
              )}
              
              {promptLoading && !emailPrompt ? (
                <div className="flex items-center justify-center py-12">
                  <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
                  <span className="ml-2 text-muted-foreground">加载中...</span>
                </div>
              ) : (
                <>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">提示词模板</label>
                    <Textarea
                      rows={18}
                      value={emailPrompt}
                      onChange={(e) => setEmailPrompt(e.target.value)}
                      placeholder="输入您的提示词模板..."
                      className="font-mono text-sm"
                    />
                    <p className="text-xs text-muted-foreground">
                      使用 Markdown 格式可以让AI输出更美观的总结
                    </p>
                  </div>

                  <div className="flex items-center justify-between pt-4">
                    <div className="flex items-center gap-2">
                      {promptSaved && (
                        <div className="flex items-center gap-2 text-sm text-green-600">
                          <CheckCircle2 className="h-4 w-4" />
                          <span>保存成功</span>
                        </div>
                      )}
                    </div>
                    <div className="flex gap-2">
                      <Button
                        variant="outline"
                        onClick={handleResetEmailPrompt}
                        disabled={promptLoading}
                      >
                        恢复默认
                      </Button>
                      <Button
                        onClick={handleSaveEmailPrompt}
                        disabled={promptLoading}
                        className="gap-2"
                      >
                        {promptLoading ? (
                          <>
                            <RefreshCw className="h-4 w-4 animate-spin" />
                            保存中...
                          </>
                        ) : (
                          <>
                            <Save className="h-4 w-4" />
                            保存提示词
                          </>
                        )}
                      </Button>
                    </div>
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 其他设置 Tab */}
        <TabsContent value="other" className="space-y-4">
          {/* Profile settings */}
          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <User className="h-5 w-5" />
                <CardTitle>个人信息</CardTitle>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-2">
                <label className="text-sm font-medium">用户名</label>
                <Input defaultValue="管理员" />
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium">邮箱</label>
                <Input type="email" defaultValue="admin@example.com" />
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium">电话</label>
                <Input type="tel" defaultValue="+86 138 0000 0000" />
              </div>
              <Button>保存更改</Button>
            </CardContent>
          </Card>

          {/* Security settings */}
          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <Shield className="h-5 w-5" />
                <CardTitle>安全设置</CardTitle>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-2">
                <label className="text-sm font-medium">当前密码</label>
                <Input type="password" />
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium">新密码</label>
                <Input type="password" />
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium">确认新密码</label>
                <Input type="password" />
              </div>
              <Button>更新密码</Button>
            </CardContent>
          </Card>

          {/* System settings */}
          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <Bell className="h-5 w-5" />
                <CardTitle>系统设置</CardTitle>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium">邮件通知</p>
                  <p className="text-sm text-muted-foreground">接收系统邮件通知</p>
                </div>
                <Button variant="outline">开启</Button>
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium">双因素认证</p>
                  <p className="text-sm text-muted-foreground">增强账户安全性</p>
                </div>
                <Button variant="outline">设置</Button>
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium">数据导出</p>
                  <p className="text-sm text-muted-foreground">导出您的所有数据</p>
                </div>
                <Button variant="outline">导出</Button>
              </div>
            </CardContent>
          </Card>

          {/* Danger zone */}
          <Card className="border-destructive">
            <CardHeader>
              <div className="flex items-center gap-2">
                <Trash2 className="h-5 w-5 text-destructive" />
                <CardTitle className="text-destructive">危险区域</CardTitle>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium">删除账户</p>
                  <p className="text-sm text-muted-foreground">
                    永久删除您的账户和所有数据
                  </p>
                </div>
                <Button variant="destructive">删除账户</Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
